package com.ex.managersystem1024.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ex.managersystem1024.entity.User;
import com.ex.managersystem1024.entity.dto.LoginDto;
import com.ex.managersystem1024.exception.ServiceException;
import com.ex.managersystem1024.mapper.UserMapper;
import com.ex.managersystem1024.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Resource
    UserMapper userMapper;


    /**
     * 新增用户
     * @param user
     * @return
     */
    public boolean add(User user) {
        if (StrUtil.isBlank(user.getUsername())) {
            user.setUsername(user.getUsername());
        }
        if (StrUtil.isBlank(user.getPassword())) {
            //默认密码123--md5加密
            String password = SecureUtil.md5("123");
            user.setPassword(password);
        }
        return save(user);
    }







    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    public User login(LoginDto loginDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username", loginDto.getUsername())
                .eq("password", SecureUtil.md5(loginDto.getPassword()));
        User dbUser = getOne(queryWrapper);
        if (dbUser == null) {
            // 抛出一个自定义的异常
            throw new ServiceException("用户名或密码错误");
        }
        // 生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(), dbUser.getPassword());
        dbUser.setToken(token);
        return dbUser;
    }


}
